using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing.Design;
using System.Net;
using System.IO;
using System.Threading;
using System.Web.Security;
using sb.core.Framework;
using System.Linq;
using xtra.domain.Subsonic3;

namespace sb.core {
    public class ModuleNode : PlaceHolder {
        #region Properties
        public string Title { get; set; }

        private Plugin plugin = null;
        #endregion

        #region Overridens
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            Plugins_In_Page node = null;
            try {
                if (ID == "RootNode") {
                    node = SiteContext.Current.RootModule;
                } else {
                    node = (from n in SiteContext.Current.Repo.All<Plugins_In_Page>()
                            where n.ParentId == (from a in SiteContext.Current.Repo.All<Plugins_In_Page>()
                                                 join b in SiteContext.Current.Repo.All<Plugin>() on a.NodeId equals b.Id
                                                 where a.ParentId == ((BaseUserControl)(this.NamingContainer)).CurrentNode.Id && b.UID == ID
                                                 select a.Id).First()
                            select n).First();
                }
                LoadControl(node);
            } catch (InvalidOperationException ex) {
            }
        }
        #endregion

        #region Method

        public BaseUserControl LoadControl(Plugins_In_Page node) {
            BaseUserControl control = null;
            plugin = node.Plugins.Single();

            try {
                control = (BaseUserControl)this.Page.LoadControl(ResolveUrl(string.Format("~/plugin/{0}/p.ascx", plugin.URI)));
                control.CurrentNode = node;
                this.Controls.Add(control);

            } catch (Exception ex) {
                this.Controls.Add(ShowError(ex.Message));
            }
            return control;
        }

        private Literal ShowError(string err) {
            return new Literal()
            {
                Text = string.Format(@"
<div style='margin:5px;padding:5px; border:solid 4px #777;color:red; background:#eee;'>
<p>Error:{0}</p>
<p>{1}<p></div>", err, plugin.URI)
            };
        }
        #endregion
    }
}
